import 'package:flutter/material.dart';
import 'package:logger/logger.dart';
import 'package:file_picker/file_picker.dart';
import 'dart:io';
import '../../core/app_config.dart';
import '../../services/system_settings_service.dart';

/// 系统设置界面
class SystemSettingsScreen extends StatefulWidget {
  const SystemSettingsScreen({super.key});

  @override
  State<SystemSettingsScreen> createState() => _SystemSettingsScreenState();
}

class _SystemSettingsScreenState extends State<SystemSettingsScreen>
    with SingleTickerProviderStateMixin {
  final Logger _logger = Logger();
  final SystemSettingsService _settingsService = SystemSettingsService();
  
  late TabController _tabController;
  bool _isLoading = false;
  String? _errorMessage;
  
  // 系统信息
  Map<String, dynamic>? _systemInfo;
  Map<String, dynamic>? _systemStats;
  
  // 备份列表
  List<Map<String, dynamic>> _backupList = [];
  
  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
    _loadSystemInfo();
    _loadBackupList();
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('系统设置'),
        bottom: TabBar(
          controller: _tabController,
          tabs: const [
            Tab(text: '系统信息'),
            Tab(text: '数据备份'),
            Tab(text: '系统统计'),
          ],
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          _buildSystemInfoTab(),
          _buildBackupTab(),
          _buildStatisticsTab(),
        ],
      ),
    );
  }

  /// 构建系统信息标签页
  Widget _buildSystemInfoTab() {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_errorMessage != null) {
      return _buildErrorView();
    }

    if (_systemInfo == null) {
      return const Center(child: Text('暂无系统信息'));
    }

    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 基本信息卡片
          _buildBasicInfoCard(),
          const SizedBox(height: 16),
          
          // 数据库信息卡片
          _buildDatabaseInfoCard(),
          const SizedBox(height: 16),
          
          // 备份信息卡片
          _buildBackupInfoCard(),
        ],
      ),
    );
  }

  /// 构建基本信息卡片
  Widget _buildBasicInfoCard() {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '基本信息',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 16),
            _buildInfoRow('应用名称', _systemInfo!['app_name'] ?? '未知'),
            _buildInfoRow('应用版本', _systemInfo!['app_version'] ?? '未知'),
            _buildInfoRow('系统运行天数', '${_systemInfo!['system_uptime'] ?? 0} 天'),
          ],
        ),
      ),
    );
  }

  /// 构建数据库信息卡片
  Widget _buildDatabaseInfoCard() {
    final dbSize = _systemInfo!['database_size'] ?? 0;
    final dbSizeMB = (dbSize / 1024 / 1024).toStringAsFixed(2);
    
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '数据库信息',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 16),
            _buildInfoRow('数据库版本', '${_systemInfo!['database_version'] ?? 0}'),
            _buildInfoRow('数据库大小', '$dbSizeMB MB'),
            _buildInfoRow('记录数量', '${(_systemInfo!['record_count'] as int?)?.toString() ?? '0'} 条'),
            _buildInfoRow('用户数量', '${(_systemInfo!['user_count'] ?? 0)} 个'),
            _buildInfoRow('数据库路径', _systemInfo!['database_path'] ?? '未知'),
            const SizedBox(height: 16),
            const Divider(),
            const SizedBox(height: 16),
            const Text(
              '测试数据管理',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 16),
            Row(
              children: [
                Expanded(
                  child: ElevatedButton.icon(
                    onPressed: _isLoading ? null : _resetTestData,
                    icon: const Icon(Icons.refresh),
                    label: const Text('重置测试数据'),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.orange,
                      foregroundColor: Colors.white,
                    ),
                  ),
                ),
                const SizedBox(width: 12),
                Expanded(
                  child: ElevatedButton.icon(
                    onPressed: _isLoading ? null : _addExtraTestData,
                    icon: const Icon(Icons.add),
                    label: const Text('添加测试数据'),
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.green,
                      foregroundColor: Colors.white,
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 8),
            ElevatedButton.icon(
              onPressed: _isLoading ? null : _showTestDataStats,
              icon: const Icon(Icons.analytics),
              label: const Text('查看数据统计'),
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.blue,
                foregroundColor: Colors.white,
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建备份信息卡片
  Widget _buildBackupInfoCard() {
    final lastBackup = _systemInfo!['last_backup'];
    final lastBackupText = lastBackup != null 
        ? '${lastBackup.year}-${lastBackup.month.toString().padLeft(2, '0')}-${lastBackup.day.toString().padLeft(2, '0')}'
        : '无';
    
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '备份信息',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 16),
            _buildInfoRow('最后备份时间', lastBackupText),
            _buildInfoRow('备份文件数量', '${_backupList.length} 个'),
            const SizedBox(height: 16),
            Row(
              children: [
                Expanded(
                  child: ElevatedButton.icon(
                    onPressed: _createBackup,
                    icon: const Icon(Icons.backup),
                    label: const Text('创建备份'),
                  ),
                ),
                const SizedBox(width: 16),
                Expanded(
                  child: OutlinedButton.icon(
                    onPressed: _cleanupBackups,
                    icon: const Icon(Icons.cleaning_services),
                    label: const Text('清理旧备份'),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  /// 构建数据备份标签页
  Widget _buildBackupTab() {
    return Padding(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 备份操作
          Card(
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  const Text(
                    '备份操作',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const SizedBox(height: 16),
                  Row(
                    children: [
                      Expanded(
                        child: ElevatedButton.icon(
                          onPressed: _createBackup,
                          icon: const Icon(Icons.backup),
                          label: const Text('创建备份'),
                        ),
                      ),
                      const SizedBox(width: 16),
                      Expanded(
                        child: OutlinedButton.icon(
                          onPressed: _selectBackupToRestore,
                          icon: const Icon(Icons.restore),
                          label: const Text('还原备份'),
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
          const SizedBox(height: 16),
          
          // 备份列表
          Expanded(
            child: Card(
              child: Padding(
                padding: const EdgeInsets.all(16),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        const Text(
                          '备份列表',
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        TextButton.icon(
                          onPressed: _loadBackupList,
                          icon: const Icon(Icons.refresh),
                          label: const Text('刷新'),
                        ),
                      ],
                    ),
                    const SizedBox(height: 16),
                    Expanded(
                      child: _isLoading
                          ? const Center(child: CircularProgressIndicator())
                          : _backupList.isEmpty
                              ? const Center(child: Text('暂无备份文件'))
                              : _buildBackupListView(),
                    ),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建备份列表视图
  Widget _buildBackupListView() {
    return ListView.builder(
      itemCount: _backupList.length,
      itemBuilder: (context, index) {
        final backup = _backupList[index];
        final fileSize = (backup['file_size'] as int) / 1024 / 1024;
        final createdTime = backup['created_time'] as DateTime;
        
        return Card(
          margin: const EdgeInsets.only(bottom: 8),
          child: ListTile(
            leading: const Icon(Icons.backup),
            title: Text(backup['file_name'] ?? '未知文件'),
            subtitle: Text(
              '大小: ${fileSize.toStringAsFixed(2)} MB\n'
              '创建时间: ${createdTime.year}-${createdTime.month.toString().padLeft(2, '0')}-${createdTime.day.toString().padLeft(2, '0')} '
              '${createdTime.hour.toString().padLeft(2, '0')}:${createdTime.minute.toString().padLeft(2, '0')}',
            ),
            trailing: PopupMenuButton<String>(
              onSelected: (value) => _handleBackupAction(value, backup),
              itemBuilder: (context) => [
                const PopupMenuItem(
                  value: 'restore',
                  child: Text('还原'),
                ),
                const PopupMenuItem(
                  value: 'delete',
                  child: Text('删除'),
                ),
              ],
            ),
          ),
        );
      },
    );
  }

  /// 构建系统统计标签页
  Widget _buildStatisticsTab() {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    if (_errorMessage != null) {
      return _buildErrorView();
    }

    if (_systemStats == null) {
      return const Center(child: Text('暂无统计信息'));
    }

    return SingleChildScrollView(
      padding: const EdgeInsets.all(16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 用户统计卡片
          _buildUserStatsCard(),
          const SizedBox(height: 16),
          
          // 记录统计卡片
          _buildRecordStatsCard(),
          const SizedBox(height: 16),
          
          // 工艺统计卡片
          _buildProcessStatsCard(),
        ],
      ),
    );
  }

  /// 构建用户统计卡片
  Widget _buildUserStatsCard() {
    final userStats = _systemStats!['user_statistics'] as Map<String, dynamic>;
    
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '用户统计',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 16),
            _buildStatRow('总用户数', '${userStats['total_users'] ?? 0}'),
            _buildStatRow('活跃用户数', '${userStats['active_users'] ?? 0}'),
            _buildStatRow('管理员用户数', '${userStats['admin_users'] ?? 0}'),
          ],
        ),
      ),
    );
  }

  /// 构建记录统计卡片
  Widget _buildRecordStatsCard() {
    final recordStats = _systemStats!['record_statistics'] as Map<String, dynamic>;
    
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '记录统计',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 16),
            _buildStatRow('总记录数', '${recordStats['total_records'] ?? 0}'),
            _buildStatRow('最近30天记录数', '${recordStats['recent_records'] ?? 0}'),
          ],
        ),
      ),
    );
  }

  /// 构建工艺统计卡片
  Widget _buildProcessStatsCard() {
    final processStats = _systemStats!['process_statistics'] as List<dynamic>;
    
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '工艺类型统计',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(height: 16),
            if (processStats.isEmpty)
              const Text('暂无工艺类型数据')
            else
              ...processStats.map((process) => _buildProcessStatRow(process)),
          ],
        ),
      ),
    );
  }

  /// 构建信息行
  Widget _buildInfoRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Flexible(
            flex: 2,
            child: Text(
              label, 
              style: const TextStyle(color: Colors.grey),
            ),
          ),
          const SizedBox(width: 8),
          Flexible(
            flex: 3,
            child: Text(
              value,
              style: const TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 16,
              ),
              textAlign: TextAlign.right,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建统计行
  Widget _buildStatRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Flexible(
            flex: 2,
            child: Text(
              label, 
              style: const TextStyle(color: Colors.grey),
            ),
          ),
          const SizedBox(width: 8),
          Flexible(
            flex: 3,
            child: Text(
              value,
              style: const TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: 16,
              ),
              textAlign: TextAlign.right,
              overflow: TextOverflow.ellipsis,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建工艺统计行
  Widget _buildProcessStatRow(Map<String, dynamic> process) {
    return Card(
      margin: const EdgeInsets.only(bottom: 8),
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Flexible(
              flex: 2,
              child: Text(
                (process['process_type'] as String?) ?? '未知工艺',
                style: const TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 16,
                ),
                overflow: TextOverflow.ellipsis,
              ),
            ),
            const SizedBox(width: 8),
            Flexible(
              flex: 1,
              child: Text(
                '${(process['record_count'] as int?)?.toString() ?? '0'} 条记录',
                style: const TextStyle(
                  color: Colors.grey,
                  fontSize: 14,
                ),
                textAlign: TextAlign.right,
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建错误视图
  Widget _buildErrorView() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(
            Icons.error_outline,
            size: 64,
            color: Colors.red,
          ),
          const SizedBox(height: 16),
          Text(
            _errorMessage ?? '加载失败',
            style: const TextStyle(color: Colors.red),
          ),
          const SizedBox(height: 24),
          ElevatedButton(
            onPressed: _retry,
            child: const Text('重试'),
          ),
        ],
      ),
    );
  }

  /// 加载系统信息
  Future<void> _loadSystemInfo() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      _logger.d('开始加载系统信息');
      final info = await _settingsService.getSystemInfo();
      final stats = await _settingsService.getSystemStatistics();
      setState(() {
        _systemInfo = info;
        _systemStats = stats;
        _isLoading = false;
      });
      _logger.i('系统信息加载成功');
    } catch (e) {
      _logger.e('加载系统信息失败: $e');
      setState(() {
        _errorMessage = '加载系统信息失败: $e';
        _isLoading = false;
      });
    }
  }

  /// 加载备份列表
  Future<void> _loadBackupList() async {
    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      _logger.d('开始加载备份列表');
      final backupList = await _settingsService.getBackupList();
      setState(() {
        _backupList = backupList;
        _isLoading = false;
      });
      _logger.i('备份列表加载成功: ${backupList.length} 个备份');
    } catch (e) {
      _logger.e('加载备份列表失败: $e');
      setState(() {
        _errorMessage = '加载备份列表失败: $e';
        _isLoading = false;
      });
    }
  }

  /// 创建备份
  Future<void> _createBackup() async {
    try {
      _logger.d('开始创建备份');
      
      setState(() {
        _isLoading = true;
      });

      final backupPath = await _settingsService.backupDatabase();
      
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('备份创建成功: ${backupPath.split('/').last}'),
            backgroundColor: Colors.green,
          ),
        );
      }
      
      // 重新加载数据
      await _loadSystemInfo();
      await _loadBackupList();
      
      _logger.i('备份创建成功: $backupPath');
    } catch (e) {
      _logger.e('创建备份失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('创建备份失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  /// 选择备份文件进行还原
  Future<void> _selectBackupToRestore() async {
    try {
      _logger.d('开始选择备份文件');
      
      final result = await FilePicker.platform.pickFiles(
        dialogTitle: '选择备份文件',
        allowedExtensions: ['db'],
        type: FileType.custom,
      );
      
      if (result != null && result.files.isNotEmpty) {
        final filePath = result.files.first.path!;
        await _restoreBackup(filePath);
      }
    } catch (e) {
      _logger.e('选择备份文件失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('选择备份文件失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  /// 还原备份
  Future<void> _restoreBackup(String backupPath) async {
    try {
      _logger.d('开始还原备份: $backupPath');
      
      // 验证备份文件
      final isValid = await _settingsService.validateBackup(backupPath);
      if (!isValid) {
        throw Exception('备份文件无效或已损坏');
      }
      
      // 确认还原操作
      final confirmed = await showDialog<bool>(
        context: context,
        builder: (context) => AlertDialog(
          title: const Text('确认还原'),
          content: const Text('还原操作将覆盖当前数据库，此操作不可逆。确定要继续吗？'),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(false),
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () => Navigator.of(context).pop(true),
              style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
              child: const Text('确定还原'),
            ),
          ],
        ),
      );
      
      if (confirmed != true) {
        return;
      }
      
      setState(() {
        _isLoading = true;
      });

      await _settingsService.restoreDatabase(backupPath);
      
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('数据库还原成功，请重启应用'),
            backgroundColor: Colors.green,
          ),
        );
      }
      
      _logger.i('备份还原成功: $backupPath');
    } catch (e) {
      _logger.e('还原备份失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('还原备份失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  /// 处理备份操作
  Future<void> _handleBackupAction(String action, Map<String, dynamic> backup) async {
    switch (action) {
      case 'restore':
        await _restoreBackup(backup['file_path']);
        break;
      case 'delete':
        await _deleteBackup(backup);
        break;
    }
  }

  /// 删除备份
  Future<void> _deleteBackup(Map<String, dynamic> backup) async {
    try {
      _logger.d('开始删除备份: ${backup['file_name']}');
      
      // 确认删除操作
      final confirmed = await showDialog<bool>(
        context: context,
        builder: (context) => AlertDialog(
          title: const Text('确认删除'),
          content: Text('确定要删除备份文件 "${backup['file_name']}" 吗？'),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(false),
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () => Navigator.of(context).pop(true),
              style: ElevatedButton.styleFrom(backgroundColor: Colors.red),
              child: const Text('确定删除'),
            ),
          ],
        ),
      );
      
      if (confirmed != true) {
        return;
      }
      
      await _settingsService.deleteBackup(backup['file_path']);
      
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('备份删除成功: ${backup['file_name']}'),
            backgroundColor: Colors.green,
          ),
        );
      }
      
      // 重新加载备份列表
      await _loadBackupList();
      await _loadSystemInfo();
      
      _logger.i('备份删除成功: ${backup['file_name']}');
    } catch (e) {
      _logger.e('删除备份失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('删除备份失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  /// 清理旧备份
  Future<void> _cleanupBackups() async {
    try {
      _logger.d('开始清理旧备份');
      
      setState(() {
        _isLoading = true;
      });

      final deletedCount = await _settingsService.cleanupOldBackups(keepCount: 10);
      
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('清理完成，删除了 $deletedCount 个旧备份'),
            backgroundColor: Colors.green,
          ),
        );
      }
      
      // 重新加载备份列表
      await _loadBackupList();
      await _loadSystemInfo();
      
      _logger.i('旧备份清理完成，删除了 $deletedCount 个备份');
    } catch (e) {
      _logger.e('清理旧备份失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('清理旧备份失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  /// 重试加载
  void _retry() {
    switch (_tabController.index) {
      case 0:
        _loadSystemInfo();
        break;
      case 1:
        _loadBackupList();
        break;
      case 2:
        _loadSystemInfo();
        break;
    }
  }

  /// 重置测试数据
  Future<void> _resetTestData() async {
    try {
      _logger.d('开始重置测试数据');
      
      setState(() {
        _isLoading = true;
      });

      await _settingsService.resetTestData();
      
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('测试数据已重置'),
            backgroundColor: Colors.green,
          ),
        );
      }
      
      _logger.i('测试数据重置成功');
    } catch (e) {
      _logger.e('重置测试数据失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('重置测试数据失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  /// 添加额外测试数据
  Future<void> _addExtraTestData() async {
    try {
      _logger.d('开始添加额外测试数据');
      
      setState(() {
        _isLoading = true;
      });

      await _settingsService.addExtraTestData();
      
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('额外测试数据已添加'),
            backgroundColor: Colors.green,
          ),
        );
      }
      
      _logger.i('额外测试数据添加成功');
    } catch (e) {
      _logger.e('添加额外测试数据失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('添加额外测试数据失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  /// 查看数据统计
  Future<void> _showTestDataStats() async {
    try {
      _logger.d('开始查看数据统计');
      
      setState(() {
        _isLoading = true;
      });

      final stats = await _settingsService.getSystemStatistics();
      
      if (mounted) {
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: const Text('数据统计'),
            content: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                _buildStatRow('总用户数', '${stats['user_statistics']['total_users'] ?? 0}'),
                _buildStatRow('活跃用户数', '${stats['user_statistics']['active_users'] ?? 0}'),
                _buildStatRow('管理员用户数', '${stats['user_statistics']['admin_users'] ?? 0}'),
                _buildStatRow('总记录数', '${stats['record_statistics']['total_records'] ?? 0}'),
                _buildStatRow('最近30天记录数', '${stats['record_statistics']['recent_records'] ?? 0}'),
                if (stats['process_statistics'] != null && stats['process_statistics'].isNotEmpty)
                  ...(stats['process_statistics'] as List<dynamic>).map((process) => _buildProcessStatRow(process)),
              ],
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(),
                child: const Text('关闭'),
              ),
            ],
          ),
        );
      }
      
      _logger.i('数据统计查看成功');
    } catch (e) {
      _logger.e('查看数据统计失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('查看数据统计失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }
} 